import pandas as pd
import time
import os
import logging

import boto3

logging.basicConfig(level=logging.INFO,
                    format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
                    datefmt='%Y-%m-%d %H:%M:%S',
                    filename='scheduler_log.txt',
                    filemode='a')


def send_email(email_list, file_context):
    client = boto3.client('sesv2')

    try:
        response = client.send_email(
            # FromEmailAddress为aws认证通过后的邮件发送人地址,如果发件人为邮箱直接写邮箱即可,如果为域名则需要加@前缀
            # FromEmailAddressIdentityArn 为aws平台提供的arn
            FromEmailAddress='metene <metene@metene.com>',
            FromEmailAddressIdentityArn='arn:aws:ses:us-east-1:733299435033:identity/metene.com',
            Destination={
                'ToAddresses': [
                ],
                'CcAddresses': [
                ],
                'BccAddresses': email_list
            },

            Content={
                'Simple': {
                    'Subject': {
                        'Data': "Flash Sale - Up to 35% Off | Subscribe to Metene to Get More.",
                        'Charset': 'utf-8'
                    },
                    'Body': {
                        'Text': {
                            'Data': 'email test',
                            'Charset': 'utf-8'
                        },
                        'Html': {
                            'Data': file_context,
                            'Charset': 'utf-8'
                        }
                    }
                },
            },

            EmailTags=[
                {
                    'Name': 'test_tag_name',
                    'Value': 'NULL'
                },
            ],
            ConfigurationSetName='test',
            ReplyToAddresses=[

            ],
            FeedbackForwardingEmailAddress='metene <metene@metene.com>',
            FeedbackForwardingEmailAddressIdentityArn='arn:aws:ses:us-east-1:733299435033:identity/metene.com',

        )
        status = response["ResponseMetadata"]["HTTPStatusCode"]
        if status != 200:
            logging.info("status值为%s,发送失败", str(status))
            fault_list_operation(email_list)
        else:
            logging.info("status值为%s,发送成功", str(status))
            success_list_operation(email_list)
    except Exception as e:
        fault_list_operation(email_list)
        logging.info("发送邮件出错：%s", str(e))


def fault_list_operation(fault_list):
    with open("fault_list.txt", 'a+', encoding='utf-8') as f:
        email_str = " ".join(fault_list) + "|"
        f.write(email_str)


def success_list_operation(success_list):
    with open("success_list.txt", 'a+', encoding='utf-8') as f:
        email_str = " ".join(success_list) + "|"
        f.write(email_str)


if __name__ == '__main__':
    Path = os.path.abspath(os.path.dirname(__file__))
    excel_data = pd.read_excel(Path + "/email.xlsx", engine="openpyxl")
    emails = excel_data.iloc[1:].values
    g_email_list = []
    y_email_list = []
    for email in emails:
        if type(email[4]) == str:
            if '@' in email[4]:
                if email[4].split("@")[1] == "yahoo.com":
                    y_email_list.append(email[4])
                else:
                    g_email_list.append(email[4])
    obj = open("email2.txt")
    try:
        gmail_file_context = obj.read()
    finally:
        obj.close()

    obj = open("email3.txt")
    try:
        ymail_file_context = obj.read()
    finally:
        obj.close()

    for i in range(0, len(g_email_list), 14):
        send_email_list = g_email_list[i:i + 14]
        time.sleep(2)
        send_email(send_email_list, gmail_file_context)
        logging.info("send_email_list:%s", str(send_email_list))

    for i in range(0, len(y_email_list), 14):
        send_email_list = y_email_list[i:i + 14]
        time.sleep(2)
        send_email(send_email_list, ymail_file_context)
        logging.info("send_email_list:%s", str(send_email_list))
